<template>
  <div class="vehicle-manage">
    <div class="page-header">
      <i class="el-icon-truck"></i>
      <span>车辆管理</span>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入车牌号/车主姓名/手机号进行搜索"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
      </el-input>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="handleSearch">查询</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">删除</el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="licensePlate" label="车牌号" min-width="120" align="center"></el-table-column>
      <el-table-column prop="vin" label="车架号" min-width="180" align="center"></el-table-column>
      <el-table-column label="品牌型号" min-width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.brandType }} {{ scope.row.vehicleType }}
        </template>
      </el-table-column>
      <el-table-column prop="vehicleColor" label="车身颜色" min-width="100" align="center"></el-table-column>
      <el-table-column label="电池容量" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.batteryCapacity }} kWh
        </template>
      </el-table-column>
      <el-table-column label="续航里程" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.rangeKm }} km
        </template>
      </el-table-column>
      <el-table-column prop="customerName" label="车主姓名" min-width="120" align="center"></el-table-column>
      <el-table-column prop="phoneNumber" label="联系电话" min-width="120" align="center"></el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="formData.licensePlate" placeholder="请输入车牌号"></el-input>
        </el-form-item>

        <el-form-item label="车架号" prop="vin">
          <el-input v-model="formData.vin" placeholder="请输入车架号"></el-input>
        </el-form-item>

        <el-form-item label="品牌型号" prop="brandType">
          <el-input v-model="formData.brandType" placeholder="请输入品牌型号"></el-input>
        </el-form-item>

        <el-form-item label="车辆类型" prop="vehicleType">
          <el-input v-model="formData.vehicleType" placeholder="请输入车辆类型"></el-input>
        </el-form-item>

        <el-form-item label="车身颜色" prop="vehicleColor">
          <el-input v-model="formData.vehicleColor" placeholder="请输入车身颜色"></el-input>
        </el-form-item>

        <el-form-item label="电池容量" prop="batteryCapacity">
          <el-input-number 
            v-model="formData.batteryCapacity"
            :precision="2"
            :step="0.1"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <span class="unit-label">kWh</span>
        </el-form-item>

        <el-form-item label="续航里程" prop="rangeKm">
          <el-input-number 
            v-model="formData.rangeKm"
            :precision="0"
            :step="10"
            :min="0"
            controls-position="right"
          ></el-input-number>
          <span class="unit-label">km</span>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="车辆图片" prop="vehicleImage">
          <el-upload
            class="vehicle-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.vehicleImage" :src="formData.vehicleImage" class="vehicle-image">
            <i v-else class="el-icon-plus vehicle-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.description"
            placeholder="请输入车辆描述">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'VehicleManage',
  data() {
    // 车牌号验证规则
    const validatePlateNumber = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的车牌号'));
        }
      }
    };

    return {
      searchQuery: '',
      loading: false,
      submitLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '新增车辆',
      formData: {
        id: null,
        customerId: null,
        licensePlate: '',
        vin: '',
        brandType: '',
        vehicleType: '',
        vehicleColor: '',
        batteryCapacity: 0,
        rangeKm: 0,
        description: '',
        status: 1,
        vehicleImage: ''
      },
      formRules: {
        licensePlate: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号格式', trigger: 'blur' }
        ],
        vin: [
          { required: true, message: '请输入车架号', trigger: 'blur' },
          { pattern: /^[A-HJ-NPR-Z0-9]{17}$/, message: '请输入正确的17位车架号', trigger: 'blur' }
        ],
        brandType: [
          { required: true, message: '请输入品牌型号', trigger: 'blur' }
        ],
        vehicleType: [
          { required: true, message: '请输入车辆类型', trigger: 'blur' }
        ],
        batteryCapacity: [
          { required: true, message: '请输入电池容量', trigger: 'blur' },
          { type: 'number', min: 0, message: '电池容量必须大于0', trigger: 'blur' }
        ],
        rangeKm: [
          { required: true, message: '请输入续航里程', trigger: 'blur' },
          { type: 'number', min: 0, message: '续航里程必须大于0', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    loadData() {
      this.loading = true;
      this.$axios.get('/api/vehicle/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery ? this.searchQuery.trim() : null
        }
      })
      .then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data;
          this.total = response.data.total || this.tableData.length;
        } else {
          this.$message.error(response.data.msg || '获取车辆列表失败');
        }
      })
      .catch(error => {
        console.error('获取车辆列表失败:', error);
        this.$message.error('获取车辆列表失败，请稍后重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    handleSearch() {
      this.currentPage = 1;
      this.loadData();
    },

    handleAdd() {
      this.dialogTitle = '新增车辆';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
      });
    },

    handleEdit(row) {
      this.dialogTitle = '编辑车辆';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.formData = { ...row };
      });
    },

    handleDelete(row) {
      this.$confirm('确认删除该车辆记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/vehicle/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.loadData();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleBatchDelete() {
      if (!this.selectedRows.length) return;
      
      this.$confirm(`确认删除选中的 ${this.selectedRows.length} 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deletePromises = this.selectedRows.map(row => 
          this.$axios.delete(`/api/vehicle/${row.id}`)
        );

        Promise.all(deletePromises)
          .then(() => {
            this.$message.success('批量删除成功');
            this.loadData();
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败，请稍后重试');
          });
      }).catch(() => {});
    },

    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const isEdit = this.formData.id !== null;
          const api = isEdit ? '/api/vehicle/update' : '/api/vehicle/add';
          
          this.submitLoading = true;
          this.$axios.post(api, this.formData)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(isEdit ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                this.loadData();
              } else {
                this.$message.error(response.data.msg || (isEdit ? '修改失败' : '添加失败'));
              }
            })
            .catch(error => {
              console.error(isEdit ? '修改车辆失败:' : '添加车辆失败:', error);
              this.$message.error(isEdit ? '修改失败，请稍后重试' : '添加失败，请稍后重试');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        }
      });
    },

    handleDialogClose() {
      this.$refs.formRef.resetFields();
      this.formData = {
        id: null,
        customerId: null,
        licensePlate: '',
        vin: '',
        brandType: '',
        vehicleType: '',
        vehicleColor: '',
        batteryCapacity: 0,
        rangeKm: 0,
        description: '',
        status: 1,
        vehicleImage: ''
      };
      this.dialogVisible = false;
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPage = 1;
      this.loadData();
    },

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.loadData();
    },

    // 图片上传相关方法
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.formData.vehicleImage = response.data;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error('图片上传失败');
      }
    }
  },
  created() {
    this.loadData();
  }
}
</script>

<style scoped>
.vehicle-manage {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  font-size: 24px;
  margin-right: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-button--text + .el-button--text) {
  margin-left: 0;
}

:deep(.el-tag) {
  text-transform: uppercase;
}

.unit-label {
  margin-left: 10px;
  color: #909399;
}

.vehicle-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.vehicle-uploader:hover {
  border-color: #409EFF;
}

.vehicle-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.vehicle-image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
